//
//  ArchiveViewController.m
//  BaseTools
//
//  Created by 李挺哲 on 15/12/14.
//  Copyright © 2015年 ltz. All rights reserved.
//

#import "ArchiveViewController.h"
#import "NSString+SandBoxPath.h"
#import "People.h"
@interface ArchiveViewController (){
    NSString * dicpath;
    NSString * arrayFilePath;

}
@property (weak, nonatomic) IBOutlet UILabel *arrayContentLabel;
@property (weak, nonatomic) IBOutlet UILabel *dataLabel;

@end

@implementation ArchiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   dicpath=[NSString documentPath];
    arrayFilePath=[dicpath stringByAppendingPathComponent:@"archer.array"];
    
}

- (IBAction)archiverArray:(id)sender {
    
    
  
    NSArray * a=@[@"张三",@"李四",@"王五"];
    //归档数组
    [NSKeyedArchiver archiveRootObject:a toFile:arrayFilePath];
  
    

}
- (IBAction)unArchiverArray:(id)sender {
    
    
    //恢复数组
    NSArray *b=[NSKeyedUnarchiver unarchiveObjectWithFile:arrayFilePath];
    NSMutableString * str=[NSMutableString string];
    
    

    for (int i=0; i<b.count; i++) {

        [str appendFormat:b[i]];
        
    }
    
    _arrayContentLabel.text=str;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (IBAction)archiverMulitData:(id)sender {
    
    NSString *filePath=[dicpath stringByAppendingPathComponent:@"MutiPerson.plist"];
    NSLog(@"%@",filePath);
    People *p1=[People initPeopleWithInfo:@"li" age:@"13" phoneNum:@"13444" headImage:[UIImage imageNamed:@"头像1"]];
    
    People *p2=[People initPeopleWithInfo:@"wang" age:@"12" phoneNum:@"122222224" headImage:[UIImage imageNamed:@"头像2"]];
    //创建一块可变的数据区
    NSMutableData *data=[NSMutableData data];
    //将数据区连接到NskeyedArcher 对象
    NSKeyedArchiver *archiver =[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //开始存档对象，存档的数据会存入NSMutableData中
    [archiver encodeObject:p1 forKey:@"person1"];
    [archiver encodeObject:p2 forKey:@"person2"];
    //存档完毕时 要掉用结束编码
    [archiver finishEncoding];
    [data writeToFile:filePath atomically:YES];
    
}
- (IBAction)unArchiverMulitData:(id)sender {
    
    NSString *filePath=[dicpath stringByAppendingPathComponent:@"MutiPerson.plist"];
    NSLog(@"%@",filePath);
    NSData *data=[NSData dataWithContentsOfFile:filePath];
    NSKeyedUnarchiver *unArchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    People *p1=[unArchiver decodeObjectForKey:@"person1"];
    People *p2=[unArchiver decodeObjectForKey:@"person2"];
    NSLog(@"%@,%@",p1.name,p2.name);
    //结束记得 finishing
    [unArchiver  finishDecoding];
    NSMutableString * string=[NSMutableString string];
    [string appendFormat:[NSString stringWithFormat:@"Person1 name=%@",p1.name]];
    [string appendFormat:[NSString stringWithFormat:@"Person2 name=%@",p2.name]];
    _dataLabel.text=string;

}


@end
